import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whitelist = ['/login', '/404']
// to表示调到哪去
// from表示从哪儿调过来
// next表示放行
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    // 有token的情况
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const userInfo = store.state.user.userInfo
      if (Object.keys(userInfo).length <= 0) {
        const res = await store.dispatch('user/getUserInfo')
        console.log(res)
      }
      next()
    }
  } else {
    // 没token的情况
    if (whitelist.includes(to.path)) {
      next()
    } else {
      next({ path: '/login' })
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
